var  suff = new Date().getMilliseconds();

$(document).ready(function() {//加载前用url上token参数去登录我们系统
    var access_token=getQueryString("access_token");
    if(access_token!=null){
        getInfoByToken(access_token,function(userInfo){
            if(userInfo.hasOwnProperty("data")&&userInfo.data.hasOwnProperty("tjjcode")){
                getUserName(userInfo.data.tjjcode,function(user){
                    let req={
                        username:aesEncode(user.data.username) + "_" + suff,
                        password:aesEncode(userInfo.data.tjjcode) + "_" + suff,
                        client_id:"cloud",
                        client_secret:"cloud",
                        grant_type:"password"
                    }

                    login(req,function (res) {
                        if(res.status == 200&&res.data){
                            let data = res.data;
                            localStorage.setExpire('access_token',data.access_token,sysTimeOut);
                            localStorage.setExpire("token_type",data.token_type,sysTimeOut)
                            localStorage.setExpire("locationHref","micro_analysis",sysTimeOut)//设置默认进入的模块
                            rememberPassword(user);
                            getUserInfo();
                        }else{
                            console.log('直接登录失败：',JSON.parse(res.request.response).message)
                        }
                    })
                })
            }

        });
    }
});


window.onload=function () {
    var nmpsd;
    var nm;
    var psd;
    var cookieString = new String(document.cookie);
    var cookieHeader = "username=";
    var beginPosition = cookieString.indexOf(cookieHeader);
    cookieString = cookieString.substring(beginPosition);
    var ends = cookieString.indexOf(";");
    if (ends != -1) {
        cookieString = cookieString.substring(0, ends);
    }
    if(beginPosition > -1){
        nmpsd = cookieString.substring(cookieHeader.length);
        if(nmpsd != ""){
            beginPosition = nmpsd.indexOf("%%");
            nm = nmpsd.substring(0, beginPosition);
            psd = nmpsd.substring(beginPosition + 2);
            document.getElementById('username').value = nm;
            document.getElementById('password').value = psd;
            if(nm != "" && psd != ""){
                document.getElementById('isRememberPwd').checked = true;
            }
        }
    }
    init();
    loginverify();
}

Storage.prototype.setExpire = (key, value, expire) => {
    let obj = {
        data: value,
        time: Date.now(),
        expire: expire
    };
    //localStorage 设置的值不能为对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
}

Storage.prototype.getExpire = key => {
    let val = localStorage.getItem(key);
    if (!val) {
        return val;
    }
    val = JSON.parse(val);
    if (Date.now() - val.time > val.expire) {
        localStorage.removeItem(key);
        return null;
    }
    return val.data;
}
var key = CryptoJS.enc.Utf8.parse("cBssbHB3ZA==HKXT");
function init() {
    document.onkeydown = function (e) { // 回车提交表单
        var theEvent = window.event || e;
        var code = theEvent.keyCode || theEvent.which;
        if (code == 13) {
            $("#login-btn").click(); // #chk_match 是你 提交按钮的ID
        }
    }

    let userparams = {
        username:'zj',
        password:'111111',
        grant_type:'password',
        scope:'server'
    }
    gettjjcode(userparams);
    let access_token=getQueryString("access_token");
    console.log('access_token:',access_token)
}

// function aesEncode(str) {
//     var encryptedData = CryptoJS.AES.encrypt(str, key, {
//         mode: CryptoJS.mode.ECB,
//         padding: CryptoJS.pad.Pkcs7
//     });
//     return encryptedData.toString();
// }

//登录
function loginverify() {
    layui.use(['layer', 'form'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;

        //自定义验证规则
        form.verify({
            username: function(value){
                if(value.length < 2){
                    return '用户名至少得2个字符';
                }
            }
            ,password: [
                /^[\S]{2,18}$/
                ,'密码必须2到18位，且不能出现空格'
            ]
        });

        // 表单提交
        form.on('submit(login-submit)', function (obj) {
            var user = obj.field;
            var formData = new FormData();
            // 加密用户名密码
            var  suff = new Date().getMilliseconds();
            // formData.append("username",aesEncode(user.username) + "_" + suff);
            // formData.append("password",aesEncode(user.password) + "_" + suff);
            // formData.append("client_id","cloud");
            // formData.append("client_secret","cloud");
            // formData.append("grant_type","password");
            let req={
                username:aesEncode(user.username) + "_" + suff,
                password:aesEncode(user.password) + "_" + suff,
                client_id:"cloud",
                client_secret:"cloud",
                grant_type:"password"
            }
            login(req,function (res) {
                if(res.status == 200&&res.data){
                    let data = res.data;
                    localStorage.setExpire('access_token',data.access_token,sysTimeOut);
                    localStorage.setExpire("token_type",data.token_type,sysTimeOut)
                    rememberPassword(user);
                    getUserInfo();
                }else{
                    debugger
                    layui.use(['notice'], function(){
                        var notice = layui.notice;
                        // 提示框，1成功、2失败、3警告、4加载、5信息(蓝色图标)
                        notice.msg(JSON.parse(res.request.response).message, {icon: 2,timeout:2000});
                    });
                }
            })

            // axios({
            //     method: 'post',
            //     url:loginUrl.tokenUrl,
            //     data:formData,
            //     headers:{
            //         'Content-Type':'application/x-www-form-urlencoded'}
            // })
            //     .then(function (response) {
            //         if(response.status == 200){
            //             var data = response.data;
            //             localStorage.setExpire('access_token',data.access_token,sysTimeOut);
            //             localStorage.setExpire("token_type",data.token_type,sysTimeOut)
            //             rememberPassword(user);
            //             getUserInfo();
            //         }else {
            //             console.log(response.data)
            //         }
            //     })
            //     .catch(function (error) {
            //         layui.use(['notice'], function(){
            //             var notice = layui.notice;
            //             // 提示框，1成功、2失败、3警告、4加载、5信息(蓝色图标)
            //             notice.msg(JSON.parse(error.request.response).message, {icon: 2,timeout:2000});
            //         });
            //         // alert(JSON.parse(error.request.response).message);
            //         console.log(error);
            //         // var response = error.response;
            //         // var data = response.data;
            //         // layer.msg(data.message, {icon: 2, time: 1500});
            //     });
            return false;
        });

    });

}

// function SetCookie(username, password) {
//     var Then = new Date();
//     Then.setTime(Then.getTime() + 1866240000000);
//     document.cookie = "username=" + username + "%%" + password + ";expires=" + Then.toGMTString();
// }

// 获取用户信息
// function getUserInfo() {
//     var access_token = localStorage.getExpire("access_token");
//     axios.get(loginUrl.userInfo,{
//         params: {
//             access_token: access_token
//         }
//     })
//         .then(function (response) {
//             if(response.status == 200 &&response.data.message == "success"){
//                 let userInfo = response.data.data;
//                 if(userInfo.sysUser.delFlag==2){
//                     localStorage.setExpire("userInfo",JSON.stringify(response.data.data),sysTimeOut)
//                     location.href=fogetPageUrl;
//                 }else{
//                     localStorage.setExpire("userInfo",JSON.stringify(response.data.data),sysTimeOut)
//                     location.href=webBaseUrl+'/index.html';
//                 }
//             }
//         })
//         .catch(function (error) {
//             console.log(error);
//         });
// }


//调用对方接口获取统计局代码
// function gettjjcode(){
//     let userInfo = {
//         username:'zj',
//         password:'111111',
//         grant_type:'password',
//         scope:'server'
//     }
//     let testreq = {
//         data: userInfo,
//         key: 'yswlyswlyswlyswl',
//         param: ['password']
//     }
//
//     let password = encryption(testreq);
//
//     axios({
//         method: 'post',
//         url:loginConnect.gettjjcode,
//         data:$.param(password),
//         headers:{
//             'isToken': false,
//             'TENANT-ID': '1',
//             'Authorization': 'Basic eXN3bDp5c3ds'}
//     })
//         .then(function (response) {
//             if(response.status == 200){
//                 var data = response.data;
//                 getInfoByToken(data.access_token);
//             }else {
//                 console.log(response.data)
//             }
//         })
//         .catch(function (error) {
//             console.log(error);
//
//         });
// }
//
// //调用对方接口用token获取用户信息
// function getInfoByToken(token){
//     axios({
//         method: 'get',
//         url:loginConnect.getInfoByToken,
//         headers:{
//             'TENANT-ID': '1',
//             'Authorization': 'Bearer '+token,
//         }
//     })
//         .then(function (response) {
//             if(response.status == 200){
//                 var data = response.data;
//             }else {
//                 console.log(response.data)
//             }
//         })
//         .catch(function (error) {
//             console.log(error);
//
//         });
// }


// function getQueryString(name){
//     let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
//     let r = window.location.search.substr(1).match(reg);
//     if (r != null) {
//         return unescape(r[2]);
//     };
//     return null;
// }
















